package cn.xuchunh;

public class HeapSort {
    private static void adjust(int[] array, int start, int end) {
        int temp = array[start];
        for (int i = 2 * start + 1; i <= end; i = i * 2 + 1) {
            if (i < end) {
                i = array[i] > array[i + 1] ? i : i + 1;
            }
            if (array[i] < temp) {
                break;
            }
            array[start] = array[i];
            start = i;
        }
        array[start] = temp;
    }

    private static void sort(int[] array) {
        //建堆
        for (int i = (array.length - 1) / 2; i >= 0; i--) {
            adjust(array, i, array.length - 1);
        }

        for (int i = array.length - 1; i >= 0; i--) {
            int temp = array[0];
            array[0] = array[i];
            array[i] = temp;
            adjust(array, 0, i - 1);
        }
    }

    public static void main(String[] args) {
        int[] array = new int[]{3, 4, 53, 5621, 52, 52, 52, 542, 16, 6513, 5, 163, 561, 165, 163, 165, 165};
        sort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + ", ");
        }
    }
}
